package com.sk.weichat.db.dao;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.sk.weichat.MyApplication;
import com.sk.weichat.bean.message.GroupMessage;
import com.sk.weichat.db.SQLiteHelper;

import java.sql.SQLException;
import java.util.List;

/**
 * 访问GroupMessage数据的Dao
 * create by swy 2019-09-17
 */
public class GroupMessageDao {
    private static GroupMessageDao instance = null;
    public Dao<GroupMessage, Integer> groupMessageDao;

    private GroupMessageDao() {
        try {
            groupMessageDao = DaoManager.createDao(OpenHelperManager.getHelper(MyApplication.getInstance(), SQLiteHelper.class).getConnectionSource(), GroupMessage.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static GroupMessageDao getInstance() {
        if (instance == null) {
            synchronized (GroupMessageDao.class) {
                if (instance == null) {
                    instance = new GroupMessageDao();
                }
            }
        }
        return instance;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        OpenHelperManager.releaseHelper();
    }

    public boolean createOrUpdateGroupMsg(GroupMessage groupMessage) {
        try {
            PreparedQuery<GroupMessage> preparedQuery = groupMessageDao.queryBuilder()
                    .where().eq("ownerId", groupMessage.getOwnerId())
                    .and().eq("packetId", groupMessage.getPacketId())
                    .prepare();
            // Update会更新所有字段，不建议频繁使用
            GroupMessage existFriend = groupMessageDao.queryForFirst(preparedQuery);
            if (existFriend != null) {
                groupMessage.set_id(existFriend.get_id());
            }
            Dao.CreateOrUpdateStatus status = groupMessageDao.createOrUpdate(groupMessage);
            return status.isCreated() || status.isUpdated();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<GroupMessage> getAllGroupMsg(String ownerId) {
        List<GroupMessage> friends = null;
        try {
            PreparedQuery<GroupMessage> preparedQuery = groupMessageDao.queryBuilder()
                    .orderBy("timeSend", false)
                    .where().eq("ownerId", ownerId)
                    .prepare();
            friends = groupMessageDao.query(preparedQuery);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return friends;
    }

    public GroupMessage getGroupMessage(String ownerId, String packetId) {
        GroupMessage groupMessage;
        try {
            PreparedQuery<GroupMessage> preparedQuery = groupMessageDao.queryBuilder()
                    .where().eq("ownerId", ownerId)
                    .and().eq("packetId", packetId)
                    .prepare();
            // Update会更新所有字段，不建议频繁使用
            groupMessage = groupMessageDao.queryForFirst(preparedQuery);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return groupMessage;
    }

    public GroupMessage getLastGroupMessage(String ownerId) {
        GroupMessage groupMessage;
        try {
            QueryBuilder<GroupMessage, Integer> builder = groupMessageDao.queryBuilder();
            builder.orderBy("timeSend", false)
                    .where().eq("ownerId", ownerId);
            groupMessage = groupMessageDao.queryForFirst(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return groupMessage;
    }

    public String getLastGroupMessageContent(GroupMessage groupMessage) {
        String content = "";

        switch (groupMessage.getState()) {
            case GroupMessage.STATUS_GM_10:
                //设置管理员
                if (groupMessage.getOwnerId().equals(groupMessage.getToUserId())) {
                    content = groupMessage.getFromUserName() + " 已将你设置为群 " + groupMessage.getRoomName() + " 管理员";
                } else {
                    content = groupMessage.getFromUserName() + " 将" + groupMessage.getToUserName() + "设置为群 " + groupMessage.getRoomName() + " 管理员";
                }
                break;
            case GroupMessage.STATUS_GM_11:
                //取消管理员
                if (groupMessage.getOwnerId().equals(groupMessage.getToUserId())) {
                    content = groupMessage.getFromUserName() + " 已取消你群 " + groupMessage.getRoomName() + " 管理员身份";
                } else {
                    content = groupMessage.getFromUserName() + " 已取消 " + groupMessage.getToUserName() + "群 " + groupMessage.getRoomName() + " 管理员身份";
                }

                break;
            case GroupMessage.STATUS_GM_12:
                //你退出群
                content = "你退出群 " + groupMessage.getRoomName();
                break;
            case GroupMessage.STATUS_GM_13:
                //你被移出群
                content = groupMessage.getFromUserName() + " 已将你移出群 " + groupMessage.getRoomName();
                break;
            case GroupMessage.STATUS_GM_14:
                //其他人退出群
                content = groupMessage.getToUserName() + " 退出群 " + groupMessage.getRoomName();
                break;
            case GroupMessage.STATUS_GM_15:
                //其他人被踢出群
                content = groupMessage.getFromUserName() + " 已将 " + groupMessage.getToUserName() + "移出群 " + groupMessage.getRoomName();
                break;
            case GroupMessage.STATUS_GM_16:
                //邀请进群
                String[] ids = groupMessage.getToUserId().split(",");
                content = groupMessage.getFromUserName() + " 邀请 " + ids.length + "位好友加入群 "+groupMessage.getRoomName();
                break;
            case GroupMessage.STATUS_GM_17:
                //申请进群
                content = groupMessage.getFromUserName() + " 申请加入群 " + groupMessage.getRoomName();
                break;
            case GroupMessage.STATUS_GM_18:
                //转让群主给你
                content = groupMessage.getFromUserName() + " 将群 " + groupMessage.getRoomName() + " 转让给你";
                break;
            case GroupMessage.STATUS_GM_19:
                //转让群主给你他人
                content = groupMessage.getFromUserName() + " 将群 " + groupMessage.getRoomName() + " 转让给" + groupMessage.getToUserName();
                break;
            case GroupMessage.STATUS_GM_20:
                //你的邀请被拒绝
                content = groupMessage.getHandler() + " 已拒绝你的群 " + groupMessage.getRoomName() + " 邀请";
                break;
            case GroupMessage.STATUS_GM_21:
                //你的申请被拒绝
                content = groupMessage.getHandler() + " 已拒绝让你加入群 " + groupMessage.getRoomName();
                break;
        }
        return content;
    }

    /* 获取群通知未读数量总和 */
    public int getGroupMsgUnReadNumTotal(String ownerId) {
        List<GroupMessage> friends = null;
        try {
            PreparedQuery<GroupMessage> preparedQuery = groupMessageDao.queryBuilder()
                    .where().eq("ownerId", ownerId)
                    .and().eq("isRead", false).prepare();
            friends = groupMessageDao.query(preparedQuery);
            return friends == null ? 0 : friends.size();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 更新群通知的阅读状态为已读
     */
    public void markUserMessageRead(String ownerId) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("isRead", true);
            builder.where().eq("ownerId", ownerId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除单条群通知
     *
     * @param ownerId
     * @param packetId
     */
    public void removeGroupMsg(String ownerId, String packetId) {
        try {
            DeleteBuilder<GroupMessage, Integer> builder = groupMessageDao.deleteBuilder();
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.delete(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除所有群通知
     *
     * @param ownerId
     */
    public void removeAllGroupMsg(String ownerId) {
        try {
            DeleteBuilder<GroupMessage, Integer> builder = groupMessageDao.deleteBuilder();
            builder.where().eq("ownerId", ownerId);
            groupMessageDao.delete(builder.prepare());

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新群通知的未处理消息为失效（在退出群，取消管理员时）
     */
    public void updateMsgStateDisabled(String ownerId,String roomId) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("msgState", 3);
            builder.where().eq("ownerId", ownerId)
                    .and().eq("roomId", roomId)
                    .and().eq("msgState", 0);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateHandler(String ownerId, String packetId, String handler) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("handler", handler);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateReason(String ownerId, String packetId, String reason) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("reason", reason);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateTimeSend(String ownerId, String packetId, long timeSend) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("timeSend", timeSend);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateFromUserName(String ownerId, String packetId, String fromUserName) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("fromUserName", fromUserName);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateAllIsGroup(String ownerId, String roomId, int isGroup) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("isGroup", isGroup);
            builder.where().eq("ownerId", ownerId).and().eq("roomId", roomId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateRead(String ownerId, String packetId, boolean isRead) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("isRead", isRead);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateToUserName(String ownerId, String packetId, String toUserName) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("toUserName", toUserName);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateOpinion(String ownerId, String packetId, String opinion) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("opinion", opinion);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateMsgState(String ownerId, String packetId, int msgState) {
        UpdateBuilder<GroupMessage, Integer> builder = groupMessageDao.updateBuilder();
        try {
            builder.updateColumnValue("msgState", msgState);
            builder.where().eq("ownerId", ownerId).and().eq("packetId", packetId);
            groupMessageDao.update(builder.prepare());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}